﻿using System;
using System.Linq;
using XpressNews.SvcRef.CmtMgmt;
using XpressNews.SvcRef.NewsMgmt;
using ns = XpressNews.SvcRef.CmtMgmt;

namespace XpressNews
{
    public partial class PageArticle : System.Web.UI.Page
    {
        private ServiceNewsManagementClient cNews = null;
        private ServiceCommentManagementClient cCmt = null;
        private News news = null;
        private ns.Comment comment = null;

        public News News
        {
            get
            {
                return this.news;
            }
            set
            {
                this.news = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadNews();
                loadComments();
            }
        }

        public void btnPostComment_Click(object sender, EventArgs e)
        {
            cCmt = new ServiceCommentManagementClient("cmtBasicHttpBinding");
            comment = new ns.Comment();            
            String newsId = Request.QueryString["newsId"];

            comment.cmtId = Guid.NewGuid();
            comment.newsId = int.Parse(newsId);
            comment.cmtWriter = txtCmtWriter.Text;
            comment.cmtContent = txtCmtContent.Text;
            comment.cmtDatePost = DateTime.Now;

            if (cCmt.writeComment(comment))
            {
                Response.Redirect("~/PageArticle.aspx?newsId=" + newsId);
            }
        }

        private void loadNews()
        {
            String newsId = Request.QueryString["newsId"];
            if (String.IsNullOrEmpty(newsId))
            {
                newsId = "1";
            }

            cNews = new ServiceNewsManagementClient("newsWsHttpBinding");
            news = cNews.RetrieveNewsByID(int.Parse(newsId));
            cNews.Close();

            if (news != null)
            {
                lblNewsTitle.Text = news.newsTitle;
                lblAuthor.Text = news.author;
                lblDatePublish.Text = news.publishDate.ToString();
                lblNewsIntroduceText.Text = news.newsIntroduceText;
                lblNewsContent.Text = news.newsContent;
            }
        }

        private void loadComments()
        {
            String newsId = Request.QueryString["newsId"];
            if (String.IsNullOrEmpty(newsId))
            {
                newsId = "1";
            }
                            
            cCmt = new ServiceCommentManagementClient("cmtBasicHttpBinding");
            var lst = cCmt.searchLatestCommentByIllegal(false).Where(i => i.newsId == int.Parse(newsId));
            cCmt.Close();

            if (lst != null)
            {
                rptComments.DataSource = lst;
                rptComments.DataBind();
            }
        }
    }
}